package com.thememaker.lockstyle;

import com.thememake.common.Context;
import com.thememake.common.base.Strings;
import com.thememake.entity.ThemeFileInfo;
import com.thememake.ui.R;
import com.thememaker.lockstyle.bean.CheckOut;
import com.thememaker.lockstyle.bean.animation.Rotation;
import com.thememaker.lockstyle.control.LayoutComponentUtils;
import javafx.animation.SequentialTransition;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import java.awt.*;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.function.Consumer;

/**
 * Created by jiajun.jiang on 2017/4/26.
 */
public class LockscreenPackageDialog{

    private final ScrollPane scrollPane;
    private Stage dialogStage;
    private Label label, progressLabel;
    private Thread inner;
    private VBox errorVBox;
    private Button openButton;
    private SequentialTransition sequentialTransition;
    private ThemeFileInfo themeFileInfo;
    private boolean isDone = false;

    public void setThemeFileInfo(ThemeFileInfo themeFileInfo) {
        this.themeFileInfo = themeFileInfo;
    }

    public LockscreenPackageDialog(Stage primaryStage, String showMessage) {
        dialogStage = new Stage();

        // 窗口父子关系
        dialogStage.initModality(Modality.APPLICATION_MODAL);
        dialogStage.initOwner(primaryStage);
        dialogStage.setTitle("锁屏打包");
        dialogStage.setResizable(false);
        dialogStage.getIcons().add(new Image(
                getClass().getResourceAsStream(Context.getDrawable(R.drawable.launcher))));
        dialogStage.setOnCloseRequest(new WindowsCloseEvent(dialogStage, primaryStage));

        // progress bar
        if (Strings.isNullOrEmpty(showMessage)) {
            showMessage = "数据加载中, 请稍后...";
        }
        label = new Label(showMessage);
        label.setStyle("-fx-text-fill: #706B95; -fx-alignment:center;");
        label.setPrefWidth(300);
        label.setMaxWidth(300);
        label.setMinWidth(300);
        label.setFont(new Font(16));
        label.setPadding(new Insets(10, 0, 0, 0));
        VBox vBox = new VBox();
        vBox.setSpacing(10);
        vBox.setBackground(Background.EMPTY);
        vBox.setAlignment(Pos.CENTER);
        vBox.getStylesheets().add("style/lockstylemain.css");
        HBox progressBox = new HBox();
        progressBox.setAlignment(Pos.CENTER);
        progressBox.setSpacing(20);
        VBox leftBox = new VBox();
        leftBox.setAlignment(Pos.CENTER);
        leftBox.setSpacing(10);
        progressLabel = new Label("0%");
        progressLabel.setStyle("-fx-text-fill: #FC4C83");
        progressLabel.setFont(new Font(12));
        VBox vBoxAnim = initAnimBox();
        leftBox.getChildren().addAll(vBoxAnim, progressLabel);
        progressBox.getChildren().add(leftBox);
        progressBox.getChildren().add(label);
        HBox hBox = new HBox();
        hBox.setSpacing(20);
        hBox.setAlignment(Pos.CENTER);
        openButton = new Button("打开锁屏目录");
        openButton.setPrefSize(120, 40);
        openButton.setId("diy-button");
        openButton.setOnAction(event -> {
            if (themeFileInfo != null) {
                EventQueue.invokeLater(() -> {
                    try {
                        Desktop.getDesktop().open(Paths.get(themeFileInfo.getThemeDir().getPath(), themeFileInfo.getThemeType(), ThemeFileInfo.LOCKSTYLE_NAME, "lockscreen").toFile());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
        });
        openButton.setDisable(true);
        hBox.getChildren().addAll( openButton);
        scrollPane = new ScrollPane();
        scrollPane.setPrefHeight(350);
        errorVBox = new VBox();
        scrollPane.setContent(errorVBox);
        scrollPane.setPadding(new Insets(10));
        vBox.getChildren().addAll(progressBox, hBox, scrollPane);
        Scene scene = new Scene(vBox, 900, 500, Color.LIGHTGREEN);
        scene.setFill(null);
        dialogStage.setScene(scene);
    }

    private VBox initAnimBox() {
        VBox vBoxAnim = new VBox();
        vBoxAnim.setPrefWidth(64);
        vBoxAnim.setPrefHeight(76);
        vBoxAnim.setAlignment(Pos.CENTER);
        vBoxAnim.setBackground(new Background(new BackgroundImage(new Image(getClass().getResourceAsStream(Context.getDrawable(R.drawable.ic_progress_bg))),
                BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, new BackgroundSize(64, 76, false, false, false, false))));
        ImageView imageView = new ImageView();
        imageView.setFitWidth(64);
        imageView.setFitHeight(76);
        imageView.setImage(new Image(getClass().getResourceAsStream(Context.getDrawable(R.drawable.ic_progress_top))));
        List<Rotation> rotationList = new ArrayList<>();
        Rotation rotation = new Rotation();
        rotation.setAngle("0");
        rotation.setTime("0");
        rotationList.add(rotation);
        Rotation rotation1 = new Rotation();
        rotation1.setAngle("360");
        rotation1.setTime("1000");
        rotationList.add(rotation1);
        sequentialTransition = AnimationUtils.initRotationAnimation(imageView, rotationList, 1);
        sequentialTransition.play();
        vBoxAnim.getChildren().add(imageView);
        return vBoxAnim;
    }


    public void updateProgressMessage(String message) {
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                if (label != null) {
                    label.setText(message);
                }
            }
        });
    }

    public void packageSuccess(){
        isDone = true;
        if (sequentialTransition != null) {
            sequentialTransition.stop();
        }
        if (themeFileInfo != null) {
            openButton.setDisable(false);
        }
        if (label != null) {
            label.setText("已为您打包成功!");
        }
    }
    public void packageSuccess(boolean bl){
        isDone = true;
        if (sequentialTransition != null) {
            sequentialTransition.stop();
        }
        if (themeFileInfo != null) {
            openButton.setDisable(false);
        }
        if (label != null) {
            if(bl){
                label.setText("已为您打包成功!");
            }else {
                label.setText("打包失败请重试!");
            }

        }
    }

    public void showProgressBar(final Task<?> task, Consumer<String> consumer) {
        inner = new Thread(task);
        inner.start();
        isDone = false;
        task.setOnSucceeded(event -> {
            if (consumer != null) {
                consumer.accept("success");
            }
        });
        dialogStage.show();
    }

    public Stage getDialogStage() {
        return dialogStage;
    }

    public void closeProgressBar() {
        dialogStage.close();
    }

    public void printError(CheckOut checkOut) {
        Platform.runLater(() -> {
            boolean bl = true;
            if(checkOut.getStateResult()==1){
                bl=false;
            }else if(checkOut.getStateResult()==0){
                bl=true;
                LayoutComponentUtils.content_Determine = false;
            }
            errorVBox.getChildren().add(getErrorLabel((String) checkOut.getContent(),bl));
            System.out.println("測試打包---------------"+checkOut.getContent());
            scrollPane.setVvalue(1);
        });
    }

    public void updateProgress(String progress) {
        Platform.runLater(() -> {
            if (progressLabel != null) {
                progressLabel.setText(progress);
            }
        });
    }

    private TextField getErrorLabel(String errorString,boolean isError) {
        TextField field = new TextField("This is a copyable label which is implemented by a TextField.");
        field.setEditable(false);
        field.setPadding(new Insets(3, 10, 3, 10));
        field.setPrefWidth(875);
        if (isError) {
            field.setText("错误 >>> "+errorString);
            field.setId("textfield-error");

        } else {
            if(LayoutComponentUtils.head_judge && LayoutComponentUtils.content_Determine){
                field.setText("警告 >>> "+errorString);
                field.setId("textfield-warning");
            }else {
                field=null;
            }


        }
        return field;
    }


    public class WindowsCloseEvent implements EventHandler<WindowEvent> {

        private Stage stage;
        private Stage primaryStage;

        public WindowsCloseEvent(Stage stage, Stage primaryStage) {
            this.stage = stage;
            this.primaryStage = primaryStage;
        }

        @Override
        public void handle(WindowEvent event) {
            event.consume();
            System.err.println("点击关闭");
            if (isDone){
                stage.close();
                primaryStage.close();
            }
        }
    }

}
